// ignore_for_file: non_constant_identifier_names
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:wallpaper_app/api/wallpaper360.dart';
import 'package:wallpaper_app/components/Images/image_load.dart';
import 'package:wallpaper_app/model/options_base.dart';
import 'package:wallpaper_app/pages/images/4k/image_list_360.dart';
import 'package:wallpaper_app/pages/search/search_image.dart';
import 'package:wallpaper_app/tools/route_animation.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  List categoryList = [];
  bool _isLoaded = false; // 防止重复请求

  Future<void> getCategory() async {
    if (_isLoaded) return; // 已加载则不再请求
    Response response = await get360getCategory(id: 0, count: 100);
    if (response.statusCode == 200) {
      setState(() {
        categoryList = response.data['data'];
        _isLoaded = true;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getCategory();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final theme = Theme.of(context).colorScheme;  
    return Scaffold(
      body: Stack(
        children: [
          _buildCategory(theme),
          Positioned(
            top: 20,
            left: 0,
            right: 0,
            child: Center(
              child: SizedBox(
                width: MediaQuery.of(context).size.width * 0.5,
                child: Material(
                  color: theme.primaryContainer,
                  borderRadius: BorderRadius.circular(10),
                  elevation: 3,
                  clipBehavior: Clip.antiAlias,
                  child: InkWell(
                    onTap: () {
                      RouteAnimation().animateRoute(
                        context,
                        SearchImage(),
                        type: AnimationType.fade,
                      );
                    },
                    child: Animate(
                      effects: [
                        ShimmerEffect(
                          duration: 3000.ms,
                          color: theme.primary,
                        )
                      ],
                      onPlay: (controller) => controller.repeat(),
                      child: Padding(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 15,
                          vertical: 8,
                        ),
                        child: Row(
                          children: [
                            Icon(
                              Icons.search,
                              color:
                                  theme.inversePrimary,
                              size: 24,
                            ),
                            SizedBox(width: 12),
                            Expanded(
                              child: Text(
                                "点击搜索你喜欢的壁纸！",
                                style: TextStyle(
                                  fontFamily: "KaiTi",
                                  fontSize: 20,
                                  fontWeight: FontWeight.w700,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCategory(ColorScheme theme) {
    return CustomScrollView(
      slivers: [
        SliverToBoxAdapter(
          child: SizedBox(height: 100),
        ),
        SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: OptionsBase().typeColumns(context),
              childAspectRatio: 1.9,
              mainAxisSpacing: 8,
              crossAxisSpacing: 8,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                // 跟踪当前卡片的悬停状态
                bool isHovered = false;

                return StatefulBuilder(
                  builder: (context, setState) {
                    return AnimatedContainer(
                      duration: Duration(milliseconds: 300),
                      curve: Curves.easeOut,
                      transform: isHovered
                          ? Matrix4.translationValues(0, -4, 0)
                          : Matrix4.translationValues(0, 0, 0),
                      child: Card(
                        elevation: isHovered ? 5 : 3, // 悬停时增加阴影
                        margin: EdgeInsets.zero,
                        shadowColor: isHovered ? theme.primary : theme.shadow,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(3),
                        ),
                        child: ClipRRect(
                          borderRadius: BorderRadius.all(Radius.circular(3)),
                          child: Stack(
                            children: [
                              Positioned.fill(
                                child: ImageLoad(
                                  imageUrl: categoryList[index]['icon'],
                                  size: 0,
                                ),
                              ),
                              Positioned.fill(
                                child: MouseRegion(
                                  onEnter: (event) =>
                                      setState(() => isHovered = true),
                                  onExit: (event) =>
                                      setState(() => isHovered = false),
                                  child: Material(
                                    color: Colors.transparent,
                                    child: InkWell(
                                      hoverColor:
                                          Colors.white.withOpacity(0.05),
                                      splashColor:
                                          theme.primary.withOpacity(0.1),
                                      onTap: () {
                                        RouteAnimation().animateRoute(
                                          context,
                                          ImageList360(
                                            cids: categoryList[index]['old_id'],
                                          ),
                                          type: AnimationType.fade,
                                        );
                                      },
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                );
              },
              childCount: categoryList.length,
            ),
          ),
        ),
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;
}
